#include "rfid_intell.h"
#include "ui_rfid_intell.h"
#include <QKeyEvent>
#include <QAxObject>
#include <QMessageBox>
#define MAX_STR 255
#define AUTO_SINGLE      1
#define AUTO_CONTINUITY  0
#define AUTO_STOP        2
#define BUFF_ROW         2
#define BUFF_LENGTH      255
#define TARGET_SIZE      24
char cache[BUFF_ROW][BUFF_LENGTH];
char buff[255];
int num = 0;
int flag;
QStandardItemModel *model;
int gRFModuleInformation = 0;
u8 sConnectMode = RF_CONNECT_MODE_LOCAL_UART;
int AUTO_MODEL = AUTO_STOP;

rfid_intell::rfid_intell(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::rfid_intell)
{
    ui->setupUi(this);
   gDeviceConnectStatus = FALSE;
   event_tablewidget_init();
   frame();
   flag = 0;
   ui->auto_start_pb->installEventFilter(this);
   ui->auto_start_pb->setFocus();
   foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
   {
       QSerialPort serial;
       serial.setPort(info);
       if(serial.open(QIODevice::ReadWrite))
       {

           ui->COM_cb->addItem(serial.portName());
           serial.close();
       }
   }
   ui->AUTO_MODEL->setCurrentIndex(1);

}
void rfid_intell::OPTION_read()
{
    if(readTag(NULL, MEMORY_BANK_EPC, 2, 6) == 0)
        qDebug()<<"校验读取";

}
void rfid_intell::send_slots(QString mmp,int cmd)
{
    switch(cmd){
    case 0:break;
    case 1:
        if(mmp.length()<10)
        { m_rfid_data->AUTO_CMDREAD();}
        else{
          m_rfid_data->AUTO_CHECK(mmp);
        }
        break;
    case 2:
        m_rfid_data->postMessageCommand(mmp);
        break;
    }

}
void rfid_intell::AUTO_CHECK(QString mmp){
    emit this->AUTO_judge(mmp);



}
void rfid_intell::AUTO_CMDREAD()
{
    emit this->AUTO_read();
}

int rfid_intell::postMessageCommand(QString mmp)
{
    emit this->read_data_send(mmp);
    return 0;
}
rfid_intell::~rfid_intell()
{
    stopInventory();
    delete ui;
}
void rfid_intell::OPTION_judge(QString bufs)
//{
//    QString buf_flag(cache[0]);
//    if(buf_flag == bufs)
//    {
//        strcpy(cache[0],cache[1]);
//        memset(cache[1],0,BUFF_LENGTH);
//        qDebug()<<"数据移动到第一位"<<cache[0];
//        //m_uart->Write_Data("M");//点击启动
//    }
//    else {
//        qDebug()<<"写入错误";
//    }
{
    ui->EPC_lb->setText(bufs);
    QString buf_flag(buff);
    if(buf_flag == bufs)
    {
        ui->match_lb->setText("相符");
        m_uart->Write_Data("M");//点击启动
        memset(buff,0,sizeof(buff));
    }
    else {
        ui->match_lb->setText("不相符");
        qDebug()<<"写入错误"<<buf_flag;
        u8 writeData[1024];
        memset(writeData,0,1024);
        QString buf(buff);
        String2Char(buf, writeData);
        int write_flag;
        write_flag= writeTag(NULL, MEMORY_BANK_EPC, 2, 6, writeData);
        if(write_flag == 0)
        {
            qDebug()<<"再次写入";
        }
    }
}

void rfid_intell::event_tablewidget_init()
{
    model = new QStandardItemModel();
    model->setColumnCount(3);
    model->setHeaderData(0,Qt::Horizontal,"编号");
    model->setHeaderData(1,Qt::Horizontal,"时间");
    model->setHeaderData(2,Qt::Horizontal,"事件");
    ui->event_tv->setModel(model);
    //表头信息显示居左
    ui->event_tv->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
    //设置列宽不可变
    ui->event_tv->setColumnWidth(0,100);
    ui->event_tv->setColumnWidth(1,50);
    ui->event_tv->setColumnWidth(2,341);
    for(int i = 0; i < 7; i++)
     {
         model->setItem(i,0,new QStandardItem(""));
            //设置字符颜色
         model->item(i,0)->setForeground(QBrush(QColor(255, 0, 0)));
            //设置字符位置
         model->item(i,0)->setTextAlignment(Qt::AlignCenter);
         model->setItem(i,1,new QStandardItem(""));
         model->setItem(i,2,new QStandardItem(""));
     }
}
void rfid_intell::hex_conv_Char(unsigned char* pHex, unsigned char *pChar)
{
    unsigned char	iChar;

    iChar = (*pHex) / 0x10;
    if (iChar <= 9 && iChar >= 0){
        pChar[0] = iChar + '0';
    }
    else if (iChar <= 0xf && iChar >= 0xA){
        pChar[0] = iChar - 0xA + 'A';
    }

    iChar = (*pHex) % 0x10;
    if (iChar <= 9 && iChar >= 0){
        pChar[1] = iChar + '0';
    }
    else if (iChar <= 0xF && iChar >= 0xA){
        pChar[1] = iChar - 0xA + 'A';
    }

}
//转换 0x51 转换为 0x35  0x31
void rfid_intell::hexc_to_charc(unsigned char *in_dat, int len, unsigned char *out_dat)
{
    int i = 0;
    for (i = 0; i < len; i++)
    {
        hex_conv_Char(&in_dat[i], &out_dat[2 * i]);
    }
}
void rfid_intell::show_data(QString data)
{
    ui->read_data_te->setText(data);
}

int rfid_intell::rm70xxUsrCallback(int status, int type, unsigned char *data, int dataLen)
{
    unsigned char hexBuf[256] = { 0 };
    memset(hexBuf, 0, sizeof(hexBuf));
    switch(type) {
        case OPTION_TYPE_INVENTORY:  //1. 盘点
    {
   // if (status == 0) {
        INVENTORY_DATA invData;
        memcpy(&invData, data, dataLen);
        hexc_to_charc(invData.epc, invData.epcLen, hexBuf);
        //memcpy(hexBuf,RWDATA.rwData,RWDATA.rwDataLen);
        std::string strt = (char*)hexBuf;
        QString mmp = QString::fromStdString(strt);
        //rfid_intell::send_slots(mmp);
        qDebug()<<"inventory"<<QString::fromStdString(strt);
//        if(times>50)
//        {
//            stopInventory();
//            qDebug()<<"over"<<QTime::currentTime().toString();
//        }
       //               }
        break;
    }
        case OPTION_TYPE_READ:   //2.
        {
            if (status == 0) {
                RW_DATA RWDATA;
                memcpy(&RWDATA, data, dataLen);
                hexc_to_charc(RWDATA.rwData, RWDATA.rwDataLen, hexBuf);
                std::string strt = (char*)hexBuf;
                QString mmp = QString::fromStdString(strt);
                rfid_intell::send_slots(mmp,AUTO_MODEL);
            }
            else
                qDebug()<<"读操作失败"<<status;
            break;

        }
        case OPTION_TYPE_WRITE:		//3.
        if(status == 0)
        {
            qDebug()<<"写入成功";
            switch(AUTO_MODEL)
            {
            case 0:break;
            case 1:
                rfid_intell::send_slots(" ",AUTO_MODEL);
                break;
            case 2:break;
            }

        }
        else
        {
//                QMessageBox::warning(this,"error","RFID写入错误",
//                                     QMessageBox::Ok,
//                                     QMessageBox::Cancel);
            qDebug()<<"RFID写入错误";
        }
        break;
        case OPTION_TYPE_KILL:		//4.
//        {
//        if (status == 0) {
//            RW_DATA RWDATA;
//            memcpy(&RWDATA, data, dataLen);
//            hexc_to_charc(RWDATA.rwData, RWDATA.rwDataLen, hexBuf);
//            //memcpy(hexBuf,RWDATA.rwData,RWDATA.rwDataLen);
//            std::string strt = (char*)hexBuf;
//            QString mmp = QString::fromStdString(strt);
//            rfid_intell::send_slots(mmp);
//            qDebug()<<"read"<<QString::fromStdString(strt);
//                          }
//        break;
//        }
        case OPTION_TYPE_LOCK:		//5.
        {
            break;
        }
        case OPTION_TYPE_ALARM_REPORT:  //100.
        {
        qDebug()<<"6";
        break;
        }
    }

    return 0;
}
LRESULT rfid_intell::getModuleBaseInfo(WPARAM iParam1, LPARAM iParam2)
{
    QString strTmp, strRadioToolTitle = "RadioTool";
    u8 snData[56] = { 0 }, boardSnData[128] = { 0 };
    TCHAR tBoardSnData[128] = { 0 };
    int snLen = sizeof(snData)-1, boardSnLen = sizeof(boardSnData)-1;

    stopInventory();

    if (mRFModule == RF_MODULE_TYPE_RM70XX) {
        // RM70xx版本，先获取板子的序列号
        if (getBoardSerialNumber(boardSnData, &boardSnLen) == 0) {
           // tBoardSnData = (const char *)boardSnData;
        memcpy(tBoardSnData,boardSnData,sizeof(boardSnData));
        //qDebug()<<QString(QLatin1String(tBoardSnData));
        }
        else {
                qDebug()<<"设备连接失败";
                   return -1;
        }
    }

    if (getModuleSerialNumber(snData, &snLen) == 0) {
        u8 version[56] = { 0 };
        int versionLen = sizeof(version)-1;
        u8 atr[128] = { 0 };
        int atrLen = 0;

        if (getModuleSoftVersion(version, &versionLen) == 0) {
            TCHAR tVersion[128] = { 0 }, tSnData[128] = { 0 };
             memcpy(tVersion,version,sizeof(version));
              memcpy(tSnData,snData,sizeof(snData));

            if (mRFModule == RF_MODULE_TYPE_RM70XX)
            {
                strTmp.sprintf("设备连接成功！RM70XX序列号:%s, 设备序列号:%s,软件版本：%s",
                    tBoardSnData, tSnData, tVersion);
                strRadioToolTitle.sprintf("RM70XX序列号:%s, 设备序列号:%s,软件版本：%s",
                    tBoardSnData, tSnData, tVersion);
                qDebug()<<strTmp;
            }
            else {
                strTmp.sprintf("设备连接成功！设备序列号:%s,软件版本：%s", tSnData, tVersion);
                strRadioToolTitle.sprintf("设备序列号:%s,软件版本：%s", tSnData, tVersion);
                qDebug()<<strTmp;
                //qDebug()<<strRadioToolTitle;
            }

            // 加载RM8011的功率信息
            if (memcmp(snData, "RM", 2) == 0) {
                // 棋连模块
                char moduleType[3] = { 0 };
                // RM-26dBm
                memcpy(moduleType, snData + 3, 2);
                gRFModuleInformation |= atoi(moduleType);
               // m_Dlg_RM8011Setting.loadPowerLevel(gRFModuleInformation);
            }
            else {
                gRFModuleInformation |= RF_MODULE_TYPE_R2000;
                u32 antennaPortNum = 0;
                if (getAntennaPortNum(&antennaPortNum) != 0) {

                }
                else {
                    if (antennaPortNum > 1) {
                        enum {
                            RFID_RESPONSE_MODE_COMPACT = 0x00000001,
                            RFID_RESPONSE_MODE_NORMAL = 0x00000003,
                            RFID_RESPONSE_MODE_EXTENDED = 0x00000007
                        };
                        setResponseDataMode(RFID_RESPONSE_MODE_EXTENDED);
                    }
                }

            }
            gDeviceConnectStatus = TRUE;
            // 标题显示版本号信息
            return 0;
        }
    }
    else {
        if (mRFModule == RF_MODULE_TYPE_RM70XX) {
            strTmp.sprintf("RM70XX连接成功，RF设备连接失败, RM70XX序列号:%s！", tBoardSnData);
            strRadioToolTitle.sprintf("RM70XX序列号:%s", tBoardSnData);
            gRFModuleInformation |= RF_MODULE_TYPE_RM70XX;
            // 网络模式
            gDeviceConnectStatus = TRUE;
            switch (sConnectMode)
            {
            case RF_CONNECT_MODE_LOCAL_UART:
                // 串口模式
               // mBtnConnectCom.SetWindowText(_T("断 开"));
                break;
           // case RF_CONNECT_MODE_USB:
                // USB模式
                //mBtnConnectUsb.SetWindowText(_T("断 开"));
                //break;
            case RF_CONNECT_MODE_LOCAL_NET:
                // 网络模式
               // mBtnConnectNet.SetWindowText(_T("断 开"));
                break;
            }
            // 标题显示版本号信息
            return 0;
        }
        else {
        }
    }
    return -1;
}
int  rfid_intell::TCharToChar(const TCHAR *tchar, char *_char)
{
    int iLength = 0;
    QString str = tchar;
    iLength = WideCharToMultiByte(CP_ACP, 0, reinterpret_cast<const wchar_t *>(str.utf16()), str.length() + 1, NULL, 0, NULL, NULL);
    WideCharToMultiByte(CP_ACP, 0,reinterpret_cast<const wchar_t *>(str.utf16()), str.length() + 1, _char, iLength, NULL, NULL);
    return iLength;
}
int rfid_intell::Base_init()
{
    char cPortName[128] = { 0 };
    mRFModule = RF_MODULE_TYPE_R2000;
    if(gDeviceConnectStatus == FALSE)
    {
        sConnectMode = RF_CONNECT_MODE_LOCAL_UART;
        gRFModuleInformation = (mRFModule << 8);
    if (initRFID(rm70xxUsrCallback,NULL) != 0) {
             qDebug()<<"FLASE";
                return -1;
    }
    setRFModuleType(mRFModule);
    //setRFModuleType(RF_MODULE_TYPE_RM70XX);
    // 本地连接模式
    setRFConnectMode(sConnectMode);



    TCharToChar(ui->com_cb->currentText().toLatin1().data(),cPortName);
    //if (openCom(ui->com_cb->currentText().toLatin1().data(), 115200) == 0) {  //打开串口
    if (openCom(cPortName, 115200) == 0) {

          if (getModuleBaseInfo(0, 0) != 0) {
              qDebug()<<"读取设备号失败";
              qDebug()<<"释放RFID库资源";
              deinitRFID();
              return -1;
          }
            //setResponseDataMode(RFID_RESPONSE_MODE_EXTENDED);
          qDebug()<<"串口打开成功";
            gDeviceConnectStatus = TRUE;
        }

    else {
        qDebug()<<"打开串口失败";
        deinitRFID();
        }
    }
}
void rfid_intell::frame()
{
        CHAR Name[256];
        UCHAR szPortName[256];
        LONG Status;
        DWORD dwIndex = 0;
        DWORD dwName;
        DWORD dwSizeofPortName;
        DWORD Type;
        HKEY hKey;
        LPCTSTR data_Set = "HARDWARE\\DEVICEMAP\\SERIALCOMM\\";
        dwName = sizeof(Name);  //Name的大小
        dwSizeofPortName = sizeof(szPortName);  //串口数大小
        //打开一个制定的注册表键,成功返回ERROR_SUCCESS即“0”值
        long ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, data_Set, 0, KEY_READ, &hKey);
        if (ret == ERROR_SUCCESS)  //打开注册表键成功
        {
            do
            {
                Status = RegEnumValueA(hKey, dwIndex++, Name, &dwName, NULL, &Type, szPortName, &dwSizeofPortName);//读取键值
                        //(HKEY hKey,DWORD dwIndex,LPSTR lpValueName,LPDWORD lpcchValueName,LPDWORD lpReserved,LPDWORD lpType,LPBYTE lpData,LPDWORD lpcbData)
                if ((Status == ERROR_SUCCESS) || (Status == ERROR_MORE_DATA))
                {
                    QString portName;
                    std::string str = (char*)szPortName;
                    portName = QString::fromStdString(str);
                    //qDebug()<<portName;
                    ui->com_cb->insertItem(0,portName);
                }
                // 每读取一次dwName和dwSizeofPortName都会被修改
                // 注意一定要重置,否则会出现很离奇的错误,本人就试过因没有重置,
                // 出现先插入串口号大的（如COM4）,再插入串口号小的（如COM3），此时虽能发现两个串口，
                // 但都是同一串口号（COM4）的问题，同时也读不了COM大于10以上的串口
                //在每次读取后，dwName和dwSizeofPortName的值发生改变，表示读取了多少字符。在下次读取时，若dwName和dwSizeofPortName的值小于实际需要读取的长度时，则读取失败，读取为空。因此需要在每次读取前，对dwName和dwSizeofPortName需要重新赋值。
                dwName = sizeof(Name);
                dwSizeofPortName = sizeof(szPortName);
            } while ((Status == ERROR_SUCCESS) || (Status == ERROR_MORE_DATA));

            RegCloseKey(hKey);
        }

        if (ui->com_cb->count() > 0) {
            ui->com_cb->setCurrentIndex(0);
        }
}

/************************************************************************/
/* 写入函数                                                                     */
/************************************************************************/
int rfid_intell::Ready_To_Write(TAG_WRITE_BUTTON_CLICK ClickNum)
{
    int status = RFID_STATUS_OK;
    QString str_Passwprd;
    QString cs_RfidWriteBuffer;

    u8 accessPassword[4] = { 0 };
    u8 memBank, startAddr, wordLen;

    timess = 0;
    if (gDeviceConnectStatus == FALSE) {
       ui->information_lab->setText("设备未连接");
        return -1;
    }

    //judge which  button is pressed and  initialization parameter selectively
    switch(ClickNum)
    {
    case EPC_BTN_WRITE_CLICK:
        {
            //Control ID
            memBank = MEMORY_BANK_EPC;
            //write string
            cs_RfidWriteBuffer = ui->write_data_te->toPlainText();
            //load read Tag begin address
            startAddr=ui->start_addr_le->text().toLatin1().toInt();
            //load read Tag Length
             wordLen = ui->length_le->text().toLatin1().toInt();
             //Read Read EPC passwork
             str_Passwprd = ui->passwd_le->text();
            break;
        }
    case  USER_BTN_WRITE_CLICK:
        {
            //comtrol id
            memBank = MEMORY_BANK_USER;

        }
    default:
        {
            break;
        }
    }

    if ((cs_RfidWriteBuffer.length() % 4) || (cs_RfidWriteBuffer.length() == 0))
    {
        qDebug()<<"写入数据为空或格式错误！";
        return -1;
    }

    if (!str_Passwprd.isEmpty()) {
        if (str_Passwprd.length() != 8) {
            qDebug()<<"密码格式错误！";
            return -1;
        }

       String2Char(str_Passwprd, accessPassword);
    }

    u8 writeData[1024];
     memset(writeData,0,1024);
     String2Char(cs_RfidWriteBuffer, writeData);
     qDebug("writeD %s\n",writeData);

   int write_flag;

   write_flag= writeTag(NULL, memBank, startAddr, wordLen, writeData);
    if(!write_flag)
    {
        qDebug()<<"写入发送成功";
    }

    return 0;
}
int  rfid_intell::String2Char(QString str, unsigned char *_char)
{
    if (str.length() % 2)
    {
        return -1;
    }

    for (int idx = 0; idx < str.length()/2; idx++)
    {
        QString tmpStr = str.mid(idx * 2, 2);
        _char[idx] = (char)tmpStr.toInt(0,16);
    }

    return 0;
}


void rfid_intell::on_open_com_pb_clicked()
{
    Base_init();
    m_rfid_data  = new rfid_intell(this);
    connect(m_rfid_data ,SIGNAL(read_data_send(QString)),this,SLOT(show_data(QString)));
    connect(m_rfid_data ,SIGNAL(AUTO_read()),this,SLOT(OPTION_read()));
    connect(m_rfid_data ,SIGNAL(AUTO_judge(QString)),this,SLOT(OPTION_judge(QString)));
   // gDeviceConnectStatus = TRUE；
}

void rfid_intell::on_read_pb_clicked()
{
    AUTO_MODEL = 2;
//            readTag(NULL, MEMORY_BANK_EPC, 0, 8);
    Ready_To_Read(EPC_BTN_READ_CLICK);
}

/************************************************************************/
/* 读取函数                                                                     */
/************************************************************************/
int rfid_intell::Ready_To_Read(TAG_READ_BUTTON_CLICK ClickNum)
{
    QString str_Passwprd;
    u8 accessPassword[4] = { 0 };
    char memBank, startAddr, wordLen;

    if (gDeviceConnectStatus == FALSE) {
        ui->information_lab->setText("串口未打开");
        return -1;
    }

    //judge which  button is pressed and  initialization parameter selectively
    switch(ClickNum)
    {
    case EPC_BTN_READ_CLICK:
        {
            //load read Tag begin address
           // startAddr = (u8)ui->start_addr_le->text().toLatin1().data();
           startAddr=ui->start_addr_le->text().toLatin1().toInt();
        //load read Tag Length
            wordLen = ui->length_le->text().toLatin1().toInt();
            //Read Read EPC passwork
            str_Passwprd = ui->passwd_le->text();

            // Read tag Area is EPC
            memBank = MEMORY_BANK_EPC;
            break;
        }
    case  TID_BTN_READ_CLICK:
        {
            //load read Tag begin address
        startAddr=ui->start_addr_le->text().toLatin1().toInt();
     //load read Tag Length
         wordLen = ui->length_le->text().toLatin1().toInt();
         //Read Read EPC passwork
         str_Passwprd = ui->passwd_le->text();
            // Read tag Area is TID
            memBank = MEMORY_BANK_TID;

            break;
        }
    case  USER_BTN_READ_CLICK:
        {
            //load read Tag begin address
        startAddr=ui->start_addr_le->text().toLatin1().toInt();
     //load read Tag Length
         wordLen = ui->length_le->text().toLatin1().toInt();
         //Read Read EPC passwork
         str_Passwprd = ui->passwd_le->text();
            // Read tag Area is EPC
            memBank = MEMORY_BANK_USER;
            break;
        }
    }


    if (!str_Passwprd.isEmpty()) {
        if (str_Passwprd.length() != 8) {
        ui->information_lab->setText("密码格式错误！");
            return -1;
        }

        String2Char(str_Passwprd, accessPassword);
    }

  readTag(accessPassword, memBank, startAddr, wordLen);
    return 0;
}
void rfid_intell::on_write16_pb_clicked()
{
    AUTO_MODEL = 2;

        Ready_To_Write(EPC_BTN_WRITE_CLICK);
}

void rfid_intell::on_auto_start_pb_clicked()
{
//    resetInventoryFilter();
//    if(startInventory(1, 0) == 0)
//    {
//        qDebug()<<"inventory start ";
//    }
    qDebug()<<"自动打开";
    AUTO_MODEL = ui->AUTO_MODEL->currentIndex();

    ui->auto_start_pb->installEventFilter(this);
    memset(cache,0,sizeof(cache));

}

void rfid_intell::on_auto_stop_pb_clicked()
{
         stopInventory();
}

void rfid_intell::on_close_com_pb_clicked()
{
    closeCom();
    qDebug()<<"close COM";
}

void rfid_intell::on_redinfrcheck_clicked()
{
    u8 port = 0, status = 0;
       // int space;
        while (1) {
            int a=getDInStatus(1, &status);
                qDebug()<<"status="<<status<<"a="<<a;
           Sleep(1000);
        }
        return;
}
void rfid_intell::keyPressEvent(QKeyEvent *event)
{
    QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
      int keys =keyEvent->key();
      if (keys <= 127)
      {
            buff[num] = (char)keys;
            num++;
      }
      if (keyEvent->key() == Qt::Key_Enter||keyEvent->key() == Qt::Key_Return) {
          qDebug()<<buff<<"over";
          ui->Code_read_lb->setText(QString::fromLatin1(buff));
          u8 memBank = MEMORY_BANK_EPC;
         u8 writeData[1024];
         memset(writeData,0,1024);
         QString buf(buff);
         String2Char(buf, writeData);
         int write_flag;
         write_flag= writeTag(NULL, memBank, 2, 6, writeData);
         if(write_flag != 0)
         {
             qDebug()<<"写入命令发送失败";
         }
//               if(strlen(cache[BUFF_ROW-2]) == TARGET_SIZE)
//               {
//                   qDebug()<<"111";
//                   memset(cache[BUFF_ROW-1],0,BUFF_LENGTH);
//                   strcpy(cache[BUFF_ROW-1],buff);


//                   if(strlen(cache[0]) == TARGET_SIZE)
//                   {

//                       u8 memBank = MEMORY_BANK_EPC;
//                       u8 writeData[1024];
//                       memset(writeData,0,1024);
//                       QString buf(cache[0]);
//                       String2Char(buf, writeData);
//                       int write_flag;
//                       write_flag= writeTag(NULL, memBank, 2, 6, writeData);
//                       if(write_flag == 0)
//                       {
//                           qDebug()<<"写入命令发送成功";
//                       }
//                   }
//               }
//               else{
//                   for(int row = 0;row <= BUFF_ROW-2;row++)
//                   {
//                        if(strlen(cache[row]) < TARGET_SIZE)
//                        {
//                            memset(cache[row],0,TARGET_SIZE);
//                            strcpy(cache[row],buff);
//                            qDebug()<<cache[0]<<" "<<cache[1];
////                            m_uart->Write_Data("M");
//                            break;
//                        }
//                   }
//               }
          num = 0;


          // Special tab handling
      }
}

void rfid_intell::on_pushButton_clicked()
{
    QAxObject excel("Excel.Application");
    excel.setProperty("Visible", false);
    QAxObject *work_books = excel.querySubObject("WorkBooks");
    work_books->dynamicCall("Open (const QString&)", QString("E:/test.xlsx"));
    QVariant title_value = excel.property("Caption");  //获取标题
    qDebug()<<QString("excel title : ")<<title_value;
    QAxObject *work_book = excel.querySubObject("ActiveWorkBook");
    QAxObject *work_sheets = work_book->querySubObject("Sheets");  //Sheets也可换用WorkSheets

    int sheet_count = work_sheets->property("Count").toInt();  //获取工作表数目
    qDebug()<<QString("sheet count : ")<<sheet_count;
    for(int i=1; i<=sheet_count; i++)
    {
    QAxObject *work_sheet = work_book->querySubObject("Sheets(int)", i);  //Sheets(int)也可换用Worksheets(int)
    QString work_sheet_name = work_sheet->property("Name").toString();  //获取工作表名称
    QString message = QString("sheet ")+QString::number(i, 10)+ QString(" name");
    qDebug()<<message<<work_sheet_name;
    }
    if(sheet_count > 0)
    {
    QAxObject *work_sheet = work_book->querySubObject("Sheets(int)", 1);
    QAxObject *used_range = work_sheet->querySubObject("UsedRange");
    QAxObject *rows = used_range->querySubObject("Rows");
    QAxObject *columns = used_range->querySubObject("Columns");
    int row_start = used_range->property("Row").toInt();  //获取起始行
    int column_start = used_range->property("Column").toInt();  //获取起始列
    int row_count = rows->property("Count").toInt();  //获取行数
    int column_count = columns->property("Count").toInt();  //获取列数
    for(int i=row_start; i<=row_count;i++)
    {
    for(int j=column_start; j<=column_count;j++)
    {
    QAxObject *cell = work_sheet->querySubObject("Cells(int,int)", i, j);
    QVariant cell_value = cell->dynamicCall("value");  //获取单元格内容
    QString message = QString("row-")+QString::number(i, 10)+QString("-column-")+QString::number(j, 10)+QString(":");
    qDebug()<<message<<cell_value.toString();
    }
    }
    }

}

void rfid_intell::on_write_pb_clicked()
{
    int status = RFID_STATUS_OK;
    QString str_Passwprd;
    QString cs_RfidWriteBuffer;

    u8 accessPassword[4] = { 0 };
    u8 memBank, startAddr, wordLen;

    timess = 0;
    if (gDeviceConnectStatus == FALSE) {
       ui->information_lab->setText("设备未连接");
        return ;
    }

    //judge which  button is pressed and  initialization parameter selectively

            //Control ID
            memBank = MEMORY_BANK_EPC;
            //write string
            //cs_RfidWriteBuffer = ui->write_data_EPC_te->toPlainText();
            //load read Tag begin address
            startAddr=ui->start_addr_le->text().toLatin1().toInt();
            //load read Tag Length
             wordLen = ui->length_le->text().toLatin1().toInt();
             //Read Read EPC passwork
             str_Passwprd = ui->passwd_le->text();


             QString str = ui->write_data_te->toPlainText();
             QByteArray ba = str.toLatin1();
             cs_RfidWriteBuffer = ba.toHex()+"00";
            qDebug()<<cs_RfidWriteBuffer.length();
    if ((cs_RfidWriteBuffer.length() % 4) || (cs_RfidWriteBuffer.length() == 0))
    {
        qDebug()<<"写入数据为空或格式错误！";
        return ;
    }

    if (!str_Passwprd.isEmpty()) {
        if (str_Passwprd.length() != 8) {
            qDebug()<<"密码格式错误！";
            return ;
        }
       String2Char(str_Passwprd, accessPassword);
    }

    u8 writeData[1024];
     memset(writeData,0,1024);
     String2Char(cs_RfidWriteBuffer, writeData);
   int write_flag;
   write_flag= writeTag(NULL, memBank, startAddr, wordLen, writeData);
   if(write_flag != 0)
   {
       qDebug()<<"写入命令发送失败";
   }
}

void rfid_intell::on_COM_START_PB_clicked()
{
    m_uart = new uart_serial();
    m_uart->COM_UART = ui->COM_cb->currentText();
    m_uart->uart_Init();
}

void rfid_intell::on_COM_STOP_PB_clicked()
{
//    m_uart->
    m_uart->Write_Data("M");
}
